<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}


   public function filters()
      {
          return array(
              'accessControl',
          );
      }
      
       public function accessRules()
    {
        return array(
            array('allow',
                'actions'=>array('index', 'edit'),
                'roles'=>array('admin'),
            ),
            array('deny',
                'actions'=>array('delete'),
                'roles'=>array('admin'),
            ),
            array('deny',
                'actions'=>array('delete'),
                'users'=>array('*'),
            ),
        );
    }

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		// Выводим по 7 новостей
		// variable flag bool for display to slider content on index page
		$news=News::model()->recently(0,5)->findAll();  
  		//echo Yii::app()->user->id;
	
		$img_count = Information::model()->count("indexf=:indexf",array(":indexf"=>"1"));
		$rnd_inf=rand(0,$img_count-5);
		$slider = Information::model()->recently($rnd_inf,5)->findAll("indexf=:indexf",array(":indexf"=>"1"));
		$uservacancy = Job::model()->recently(0,10)->findAll();
		//echo Yii::app()->user->id;
		
		$this->render('index',array('news'=>$news,'information'=>$slider,'uservacancy'=>$uservacancy));
    
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	
	public function actionRegistration()
	{
		if(true)
		{
		$reguser=new User();
            
            // ajax validation 
            if (isset($_POST['ajax'])&& $_POST['ajax']==='reg-form')
            {
                # code...
                echo CActiveForm::validate($reguser);
                Yii::app()->end();
            }
            
             // this is registration logic
          
           if (isset($_POST['User']))
            {
                
                $reguser->attributes=$_POST['User'];
          
               
                if ($reguser->validate('reg'))
                {
                        
                    if ($reguser->model()->count("username=:username",array(':username'=>$reguser->username)))
                    {
                        //$reguser->addError('email','Такой e-mail уже зарегестрирован');
                       /// $this->render('reg', array('reguser'=>$reguser));
                        $reguser->addError('username', 'такой логин уже зарегистрирован');
                    
                        //$this->render('reg', array('reguser'=>$reguser));                     
                	}
                   
	                else if ($reguser->model()->count("email=:email", array(':email'=>$reguser->email)))
	                {
	                      $reguser->addError('email','такой e-mail уже зарегестрирован');
	                    //$this->render('reg',array('reguser'=>$reguser));                             
	                }
                else
                {
                	$user=$reguser->username;
                	$pass= $reguser->password;
                    $reguser->password=md5(md5($reguser->password));
                    $reguser->password1=md5(md5($reguser->password1));
                    $reguser->date=date('Y-m-d [H:i:s]');
                    //Автоматическая авторизация пользователя при регистрации
                    if($reguser->save())
                    {
                    	
                    	$model=new LoginForm;                  	
                    	
                    	$model->username=$user;
                    	$model->password=$pass;
                    	if($model->validate() && $model->login())
                    	{
                      		$url="/userpage/";
                    	}
                      $this->redirect($url);
                    }
                }                   
                }
            }
            
            
            $this->render('reg', array('reguser'=>$reguser));
		}
		else
		{
			$slider = Information::model()->recently(0,5)->findAll();
			$uservacancy = Job::model()->recently(0,10)->findAll();
			  $this->render('application.views.site.regblock',array('uservacancy'=>$uservacancy,'information'=>$slider));
		}
	}
	
	
	//Добавление комента AJAX
	public function actionAddComent()
 	 {
 	 	
 	  if(isset($_POST['comment']))
                {
                        $input_text = $_POST['comment'];
                        //$input_about = $_POST['input_about'];
                        $object = $_POST['object'];
                        $id_post= $_POST['id_post'];
                        $user_name = $_POST['user_name'];
                      //  $email = $_POST['email'];
                        

                }
		if(Yii::app()->request->isAjaxRequest)
            {
            	
                $comments = new Coments();
               
                $comments->id_post=$id_post;
                $comments->text=$input_text;
                $comments->date_com = date('Y-m-d [H:i:s]');
                $comments->user_name=$user_name; 
                $comments->object=$object;
               // $comments->email=$email;
                $s="";
               
                if($comments->save())
                {
                	
                	$commens_viv=Coments::model()->recently()->findAll("object=:object AND id_post=:id_post",array(":object"=>$object,":id_post"=>$id_post));
          			   echo '<h2>Comments</h2>';
						echo '<ul class="commentlist">';

			 
						$i=1;
					//Выводим все коменты
						foreach ($commens_viv as $key )
						{
							$Id_Coment = "comment_odd";
							if($i%2!=0)
							{
								$Id_Coment = "comment_even";						
							}
							
							echo '
							  <li class="'.$Id_Coment.'">
					            <div class="author"><img class="avatar" src="images/demo/avatar.gif" width="32" height="32" alt="" /><span class="name"><a href="#">'.$key->user_name.'</a></span> <span class="wrote">написал:</span></div>
					            <div class="submitdate"><a href="#">'.date("d/m/Y",strtotime($key->date_com)).'</a></div>
					            <p>'.$key->text.'</p>
					          </li>		
							';
							
							$i++;
							
						}			
			
			
					echo '</ul>';
                	
                }
                else 
                {
                	echo "<h2>Заполните все поля<h2>";
                }
              
              
                
               // echo Yii::app()->user->id;
                	
            }
 	 }
	/**
	 * Logs out the current user and redirect to homepage.
	 */
 	 //Ajax Загрузка файлов
 	 
 	 public function actionUploadfile() 
 	 {
 	 	 if(isset($_POST['file']))
                {
                        $file = $_POST['file'];
                        //$input_about = $_POST['input_about'];
                       
                        

                }
		if(Yii::app()->request->isAjaxRequest)
            {
            	echo "sdfsf";
            	echo $_POST['file'];
            	
            }
 	 }
 	 
 	 public function actionMap() 
 	 {
 	 	$this->render("map");
 	 }
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
}